from django.shortcuts import render
from django.views import View
from QQLoginTool.QQtool import OAuthQQ
from meiduo_mall import settings
from django.http import JsonResponse,HttpResponseBadRequest
from apps.oauth.models import OAuthQQUser
from django.contrib.auth import login
import json
from apps.users.models import User
from apps.oauth.common import generic_access_token,check_access_token


# Create your views here.
class QQLoginURLView(View):
    def get(self,request):
#1.接收next参数 2.创建qqLtool 3.调用URL方法 4.返回响应
 #next记录跳转的页面
        next=request.GET.get('next')
        qqlogin=OAuthQQ(client_id=settings.QQ_CLIENT_ID,client_secret=settings.QQ_CLIENT_SECRET,redirect_uri=settings.QQ_REDIRECT_URI,state=next)

        login_url=qqlogin.get_qq_url()
        return JsonResponse({'code':0,'errmsg':'done','login_url':login_url})

class QQUserView(View):
    def get(self,request):
    #1.获取请求code 2.code获取token 3.token换取openid
        code=request.GET.get('code')
        if code is None:
            return JsonResponse({'code':400,'errmsg':'缺少必要参数'})

        oauthqq = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                    redirect_uri=settings.QQ_REDIRECT_URI,state=None)
        token=oauthqq.get_access_token(code)
        openid=oauthqq.get_open_id(token)

    # 4.由openid查询用户信息存在 4.如果没有则绑定，有则跳转（状态保持，设置cookie,返回)
        try:
            qquser=OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            openid_token=generic_access_token(openid)

            return JsonResponse({'code': 300, 'access_token': openid_token})

        else:
            login(request,qquser.user)
            response=JsonResponse({'code':0,'errmsg':'done'})
            response.set_cookie('username',qquser.user.username,max_age=10*24*3600)
            return response
#post方法保存用户信息openid
    def post(self,request):
    #1.接收参数 2.验证 3.根据手机号判断用户存在，存在则验证密码，不存在则创建
#      保存信息，设置cookie返回
        data=json.loads(request.body.decode())
        mobile=data.get('mobile')
        password=data.get('password')
        openid_token=data.get('access_token') #=access_token
        sms_code=data.get('sms_code')

        openid=check_access_token(openid_token)
        if openid is None:
            return JsonResponse({'code':400,'errmsg':'过期了'})


        try:  #获取手机号
            user=User.objects.get(mobile=mobile)
        except User.DoesNotExist: #如果不存在
            user=User.objects.create_user(username=mobile,mobile=mobile,password=password)
        else:#如果存在验证密码

            if not user.check_password(password):
                return JsonResponse({'code':400,'errmsg':'密码错误'})

        OAuthQQUser.objects.create(user=user,openid=openid) #保存信息

        login(request,user)

        response=JsonResponse({'code':0,'errmsg':'done'})
        response.set_cookie('username',user.username,max_age=14*24*3600)
        return response

####
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
#1.创建实例 2.加密数据
s=Serializer(secret_key='000',expires_in=300)
token=s.dumps({'mobile':'13100000000'})
s.loads(token)






